package net.thxjj.netty;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import net.model.device.BaseBean;
import net.thxjj.extservice.MobileWebSocketClient;
import net.thxjj.service.IDeviceService;
import net.thxjj.service.IProductService;

import java.util.logging.Logger;

public  class HeartBeatBaseChannelInBoundHandler extends SimpleChannelInboundHandler<BaseBean> {
    private Logger log = Logger.getLogger(String.valueOf(this.getClass()));

    private int lossConnectCount = 0;

    protected IDeviceService deviceService;
    protected IProductService productService;
    protected MobileWebSocketClient mobileWebSocketClient;

    public HeartBeatBaseChannelInBoundHandler(IDeviceService deviceService) {
        this.deviceService = deviceService;
    }

    public HeartBeatBaseChannelInBoundHandler() {
    }

    public void setDeviceService(IDeviceService deviceService) {
        this.deviceService = deviceService;
    }

    public void setProductService(IProductService productService) {
        this.productService = productService;
    }

    public MobileWebSocketClient getMobileWebSocketClient() {
        return mobileWebSocketClient;
    }

    public void setMobileWebSocketClient(MobileWebSocketClient mobileWebSocketClient) {
        this.mobileWebSocketClient = mobileWebSocketClient;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, BaseBean s) throws Exception {

    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        log.info("已经"+lossConnectCount+"秒未收到客户端的消息了！");
        if (evt instanceof IdleStateEvent){
            IdleStateEvent event = (IdleStateEvent)evt;
            if (event.state()== IdleState.READER_IDLE){
                lossConnectCount++;
                if (lossConnectCount>90){
                    log.info("关闭这个不活跃通道！");
                    ctx.close();
                }
            }
        }else {
            super.userEventTriggered(ctx,evt);
        }
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        lossConnectCount = 0;
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
    }




}
